﻿using LdtJudge.DataEngine.Common.DateAssemble;
using LdtJudge.DataEngine.Common.MoneyAssemble;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;

namespace LdtJudge.DataEngine.Common
{
    /// <summary>
    /// 程序枚举类型
    /// </summary>
    public enum PathType
    {
        Server = 1,
        From = 2,
        Web = 3
    }
    /// <summary>
    /// 通用的数据格式化处理类
    /// </summary>
    public class CommonFormat
    {
        /// <summary>
        /// 本系统入口标签
        /// </summary>
        public enum PlatFormName
        {
            /// <summary>
            /// 工具入口
            /// </summary>
            AnalysisTool = 0,
            /// <summary>
            /// 数据同步API入口
            /// </summary>
            AnalysisApi = 1,
            /// <summary>
            /// 后台分析服务入口
            /// </summary>
            AnalysisService = 2
        }
        /// <summary>
        /// 程序类型
        /// </summary>
        public static PathType Pathtype { get; set; }

        /// <summary>
        /// 获取dynamic转String结果
        /// </summary>
        /// <param name="namic">传入值</param>
        /// <returns></returns>
        public static string DynamicByString(dynamic namic)
        {
            string value = "";
            if (namic != null)
            {
                value = namic.ToString();
            }
            return value;
        }

        /// <summary>
        /// 获取当前程序的运行路径，主要用于判断程序的调用是
        /// window  还是 web
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentProgramPath()
        {
            string path = "";
            if (Pathtype == 0)
            {
                Pathtype = (PathType)1;
            }

            if (Pathtype == PathType.Server || Pathtype == PathType.From)
            {
                path = AppDomain.CurrentDomain.BaseDirectory;
            }
            else if (Pathtype == PathType.Web)
            {
                path = AppDomain.CurrentDomain.BaseDirectory + @"\\Bin\\";
            }


            return path;
        }
        /// <summary>
        /// 将文件对象进行用JSON转换为String字符串
        /// Returns the json string.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns>System.String.</returns>
        public static string ReturnJsonString(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 将Json字符串转换为传入对象 
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns>System.String.</returns>
        public static T ReturnJsonToModel<T>(string obj)
        {
            return JsonConvert.DeserializeObject<T>(obj);
        }


        public static string FormatDateCompute(string relatDateStr, string computeWord)
        {
            string standardDate = FormatDataField("datetime", relatDateStr);

            DateTime oRelatTime = DateTime.Parse(standardDate);

            switch (computeWord)
            {
                case "当日":
                case "同日":
                    return standardDate;
                case "次日":
                case "第二天":
                case "第2天":
                    return oRelatTime.AddDays(1).ToShortDateString();
            }

            return "";
        }

        /// <summary>
        /// 按数据库字段类型，对字段值进行格式化。
        /// </summary>
        /// <param name="fieldType">字段类型</param>
        /// <param name="currFieldValue">字段值</param>
        /// <returns>格式化后的值。</returns>
        public static string FormatDataField(string fieldType, string currFieldValue)
        {
            string convertValue = currFieldValue;
            if (fieldType == "" || fieldType == "varchar" || fieldType == "nvarchar" || fieldType == "ntext")
            {
                fieldType = "string";
            }
            if ((fieldType == "int" || fieldType == "Standardamount") && !Regex.IsMatch(convertValue, @"^\d*$"))
            {
                //支持对不规范的日期区间，转化为天数！
                if (Regex.IsMatch(currFieldValue, "年|月"))
                {
                    double nYear = LdtMoneyFormat.DecodeNumberCn(Regex.Match(currFieldValue, @"[零一二三四五六七八九十\d]*(?=年)").Value);
                    double nMonth = LdtMoneyFormat.DecodeNumberCn(Regex.Match(currFieldValue, @"[零一二三四五六七八九十\d]*(?=个?月)").Value);
                    double nDay = LdtMoneyFormat.DecodeNumberCn(Regex.Match(currFieldValue, @"[零一二三四五六七八九十\d]*(?=日|天)").Value);

                    convertValue = (nYear * 360 + nMonth * 30 + nDay).ToString();
                }
                else {
                   

                        //壹，贰，叁，肆，伍，陆，柒，捌，玖，拾 仟 佰 萬
                        //一，二，三，四，五，六，七，八，九，十， 
                        AmountConvert acvent = new AmountConvert();
                    convertValue = acvent.DataConvertNumber(convertValue, false);
                    return convertValue;

                }
                   
            }

            if (fieldType == "datetime")
            {
                if (Regex.IsMatch(convertValue, @"[〇零一二三四五六七八九十\s]+"))
                {
                    string year = Regex.Match(convertValue, "[^年]+(?=年)").Value;
                    string month = Regex.Match(convertValue, "[^年月]+(?=月)").Value;
                    string day = Regex.Match(convertValue, "[^年月日]+(?=日)").Value;

                    year = DateTimeFormat.FormatChDateTimeNumber(year).ToString();
                    month = DateTimeFormat.FormatChDateTimeNumber(month).ToString();
                    day = DateTimeFormat.FormatChDateTimeNumber(day).ToString();
                    day = (day == "0") ? "01" : day;

                    convertValue = year + "-" + month + "-" + day;
                }
                DateTime oNewTime;
                if (!DateTime.TryParse(convertValue, out oNewTime))
                    convertValue = string.Empty;
            }

            return convertValue;
        }

        #region 添加表数据
        /// <summary>
        /// 获取表数据的集合
        /// </summary>
        /// <param name="keyValuePairs">键值集合</param>
        /// <param name="Key">键</param>
        /// <returns></returns>
        public static List<Dictionary<string, string>> GetTableDicValue(Dictionary<string, List<Dictionary<string, string>>> keyValuePairs, string Key)
        {
            if (keyValuePairs != null && keyValuePairs.ContainsKey(Key.ToLower()))
            {
                return keyValuePairs[Key.ToLower()];
            }
            else
            {
                List<Dictionary<string, string>> rows = new List<Dictionary<string, string>>();
                return rows;
            }
        }
        /// <summary>
        /// 添加表数据
        /// </summary>
        /// <param name="keyValuePairs">数据集合</param>
        /// <param name="Key">被添加的表</param>
        /// <param name="row">需要添加的行数据</param>
        public static void AddTableDicValue(Dictionary<string, List<Dictionary<string, string>>> keyValuePairs, string Key, Dictionary<string, string> row)
        {
            if (!keyValuePairs.ContainsKey(Key.ToLower()))
            {
                List<Dictionary<string, string>> rows = new List<Dictionary<string, string>>();
                keyValuePairs.Add(Key.ToLower(), rows);
            }
            keyValuePairs[Key.ToLower()].Add(row);
        }


        #endregion


        #region 字典Dic数据的修改与添加
        /// <summary>
        /// 根据键值内容集合，根据键返回值
        /// </summary>
        /// <param name="keyValuePairs">键值集合</param>
        /// <param name="Key">键</param>
        /// <returns></returns>
        public static string GetDicValue(IDictionary<string, string> keyValuePairs, string Key)
        {
            if (keyValuePairs != null && keyValuePairs.ContainsKey(Key.ToLower()))
            {
                return keyValuePairs[Key.ToLower()];
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 将当前的内容添加到指定的集合中
        /// </summary>
        /// <param name="keyValuePairs">键值集合</param>
        /// <param name="Key">键</param>
        /// <param name="value">键</param>
        /// <returns></returns>
        public static void AddDicValue(Dictionary<string, string> keyValuePairs, string Key, string value)
        {
            if (keyValuePairs.ContainsKey(Key.ToLower()))
            {
                keyValuePairs[Key.ToLower()] = value;
            }
            else
            {
                keyValuePairs.Add(Key.ToLower(), value);
            }
        }


        #endregion
       
        #region 将键值数据转实体对象
        /// <summary>
        /// 将Dic集合数据转为对象数据
        /// </summary>
        /// <typeparam name="T">需要转换的对象</typeparam>
        /// <param name="keyValues">Dic数据</param>
        /// <returns></returns>
        public static T DicToObject<T>(Dictionary<string, string> keyValues) where T : class
        {
            T model = Activator.CreateInstance<T>();
            System.Reflection.PropertyInfo[] properties = model.GetType().GetProperties();
            if (properties.Length > 0 && keyValues.Count() > 0)
            {
                foreach (var property in properties)
                {
                    if (keyValues.ContainsKey(property.Name.ToLower()))
                    {
                        property.SetValue(model, keyValues[property.Name.ToLower()], null);
                    }
                }
            }
            return model;
        }


        #endregion

        #region 将键值对数据转dataTable
        /// <summary>
        /// 根据传入的键值集合返回一个数据表集合
        /// </summary>
        /// <param name="dictable">键表数据</param>
        /// <returns></returns>
        public static List<DataTable> GetDictConvertDataTable(Dictionary<string, List<Dictionary<string, string>>> dictable)
        {
            List<DataTable> dataTables = new List<DataTable>();

            foreach (var Temptable in dictable)
            {
                DataTable table = new DataTable();
                table.TableName = Temptable.Key;//获取到表名称

                foreach (var rows in Temptable.Value)
                {//获取到表数据集合
                    foreach (var colName in rows.Keys)
                    {//遍历所有的key为表的列；
                        if (!table.Columns.Contains(colName))
                        {
                            table.Columns.Add(colName, typeof(string));
                        }

                    }
                    DataRow dtrow = table.NewRow();//创建一行数据
                    foreach (KeyValuePair<string, string> item in rows)
                    {//将所有的对应数据添加其中
                        dtrow[item.Key] = item.Value;
                    }
                    table.Rows.Add(dtrow);
                }

                dataTables.Add(table);
            }

            return dataTables;
        }

        /// <summary>
        /// 传入键值，返回一个数据表
        /// </summary>
        /// <param name="dicList">键值数据</param>
        /// <returns></returns>
        public static DataTable GetDictConvertDataTable(List<Dictionary<string, string>> dicList)
        {
            DataTable table = new DataTable();
            foreach (var dic in dicList)
            {
                foreach (var colName in dic.Keys)
                {//遍历所有的key为表的列；
                    if (!table.Columns.Contains(colName))
                        table.Columns.Add(colName, typeof(string));
                }

                DataRow dtrow = table.NewRow();//创建一行数据
                foreach (KeyValuePair<string, string> item in dic)
                {//将所有的对应数据添加其中
                    dtrow[item.Key] = item.Value;
                }
                table.Rows.Add(dtrow);
            }

            return table;
        }


        #endregion

        #region Xml 逻辑处理
        /// <summary>
        /// 替换xml中的非法字符
        /// </summary>
        /// <param name="sourceXml">xml原文</param>
        /// <returns></returns>
        public static string EscapeXml(string sourceXml)
        {
            string result = "";

            result = sourceXml.Replace("&", "&amp;");

            return result;
        }


        #endregion

        /// <summary>
        /// 将datarow转换为dic 数据
        /// </summary>
        /// <param name="row">DataRow</param>
        /// <returns></returns>
        public static Dictionary<string, string> DataRowToDic(DataRow row)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            foreach (DataColumn column in row.Table.Columns)
            {
                result.Add(column.ColumnName.ToLower(), Convert.ToString(row[column]));
            }
            return result;
        }

    }
}
